package com.ithuameng.admin.converter;

import com.google.common.collect.Maps;
import com.ithuameng.admin.enums.AdminEnumStrValue;
import org.springframework.core.convert.converter.Converter;

import java.util.Map;

/**
 * 自定义枚举转换
 * 
 * @author ithuameng
 *
 * @param <枚举类型>
 */
public class String2EnumConverter<T extends AdminEnumStrValue> implements Converter<String, T> {

	private Map<String, T> enumMap = Maps.newHashMap();

	public String2EnumConverter(Class<T> enumType) {
		T[] enums = enumType.getEnumConstants();
		for (T e : enums) {
			enumMap.put(e.getValue(), e);
		}
	}

	@Override
	public T convert(String source) {
		T t = enumMap.get(source);
		if (t == null) {
			throw new IllegalArgumentException("无法匹配对应的枚举类型");
		}
		return t;
	}
}
